home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Language/OS - Multiplatform Resource Library
/
LANGUAGE OS.iso
/
simula
/
books
/
books.lha
/
kirkerud
/
guess.sim
< prev
next >
Wrap
Text File
|
1993-08-16
|
2KB
|
46 lines
! Example 3.9;
begin
integer guess, below, above, number_of_guesses;
Boolean guessed_the_number;
character given_char;
outtext( "Think of an integer bigger than 0 and less than 1000");
outimage;
below := 0; above := 1000;
! These values are such that below < unknown number < above;
guessed_the_number := false;
number_of_guesses := 0;
while not guessed_the_number do
begin
! Here the following condition always holds:
! below < unknown number < above;
guess := (below + above)//2;
! A good guess when nothing else is known,
! is that the unknown is in the middle;
number_of_guesses := number_of_guesses + 1;
outtext( "Is it "); outint(guess, 0); outchar('?'); outimage;
outtext(" If it is, type y."); outimage;
outtext(" If not, type + if the guess is too small,"
" type - if it is too large> "); breakoutimage;
inimage; given_char := inchar;
if given_char = 'y' then guessed_the_number := true else
if given_char = '+' then below := guess else above := guess;
! If the guess was not correct, this change of either below or above
! is such that the condition
! below < unknown number < above
! still holds.
! Furthermore, the distance from below to above is less
! than it was. This means that progress is made, and sooner
! or later there can only be room for one integer between below
! and above. A correct ``guess'' will then be made the next time.;
end;
outtext( "The unknown number was found after only ");
outint(number_of_guesses, 0); outtext( " guesses!"); outimage;
end